import  React, { Component } from 'react'
import { DatePicker, Spin, message } from 'antd'
import DetailsStyle from './detail.module.sass'
import '../../static/style/detail/detail.sass'
import NoneBorderTitle from '../common_title/none_border_header'
import HeaderTitle from '../common_title/common_header_title'
import CommonCharts from '../common_chart/index'
import NavTable from '../common_table/details/nav_table'
import ScaleTable from '../common_table/details/scale_table'
import SubTable from '../common_table/details/sub_table'
import moment from 'moment'
import locale from 'antd/es/date-picker/locale/zh_CN'
import { _getMockNav, _getUnitList, _getSubSearch, _getScaleList, _getSubScale, _getSubNav } from '../../apis/details'
import url from 'url'
import {areaColors, chartsColors, linesOptions} from '../../Utils/charts_config/charts_config'

const { query } = url.parse(window.location.href, true)

export default class SubProduct extends Component {
    constructor (props) {
        super(props)
        this.state = {
            scaleLoading: false,
            navLoading: false,
            startDate: null,
            endDate: null,
            orgScreen: [],
            typeScreen: [],
            org_ids: [],
            type_codes: [],
            switchLoading: false
        }
    }

    render () {
        return (<div className={`analysis_container`}>
            <div className={`container_bg_fff ${DetailsStyle.switch_wrapper}`}>
                <h3 className={`${DetailsStyle.search_title}`}>过滤条件</h3>

                <div className={`${DetailsStyle.switch_container} display_flex`}>
                    <span className={`${DetailsStyle.switch_content_tit}`}>时&nbsp;&nbsp; &nbsp; &nbsp;  间：</span>
                    <DatePicker locale={locale} placeholder={`开始时间`} value={this.state.startDate} onChange={this.changeStartDate.bind(this)} /> <em className={`split_em_date`}>~</em>
                    <DatePicker locale={locale} placeholder={`结束时间`} value={this.state.endDate} onChange={this.changeEndDate.bind(this)} />
                </div>
                <Spin spinning={this.state.switchLoading}>
                    <div className={`${DetailsStyle.switch_container} ${DetailsStyle.flex_align_start} display_flex`}>
                        <span className={`${DetailsStyle.switch_content_tit}`}>资产类别：</span>
                        <dl className={`switch_container ${DetailsStyle.flex_wrap_none}`}>
                            <dt onClick={this.resetParams.bind(this, 'type_codes')} className={`${this.state['type_codes'].length > 0 ? '' : DetailsStyle.dt_select}`}>不限</dt>
                            {this.state.typeScreen.length > 0 ? this.state.typeScreen.map((item, index) => <dd onClick={this.checkSwitch.bind(this, 'type_codes', item['type_code'])} key={index}>{`${item['type_name']}`}</dd>) : '暂无数据'}
                        </dl>
                    </div>
                    <div className={`${DetailsStyle.switch_container} ${DetailsStyle.flex_align_start} display_flex`}>
                        <span className={`${DetailsStyle.switch_content_tit}`}>投顾名称：</span>
                        <dl className={`switch_container ${DetailsStyle.flex_wrap_none}`}>
                            <dt onClick={this.resetParams.bind(this, 'org_ids')} className={`${this.state['org_ids'].length > 0 ? '' : DetailsStyle.dt_select}`}>不限</dt>
                            {this.state.orgScreen.length > 0 ? this.state.orgScreen.map((item, index) => <dd onClick={this.checkSwitch.bind(this, 'org_ids', item['org_id'])} data-ids={item['org_id']} key={index}>{`${item['org_name']}`}</dd>) : '暂无数据'}
                        </dl>
                    </div>
                </Spin>
            </div>

            <div className={`container_bg_fff ${DetailsStyle.none_border_container}`}>
                <NoneBorderTitle iconStatus={false } title={`单位净值序列`} />
                <NavTable ref={`navTable`} ref={`navTables`} _getUnitList={this._getUnitTableList.bind(this)}/>
            </div>

            <div className={`container_bg_fff mt_20 ${DetailsStyle.none_border_container}`}>
                <NoneBorderTitle iconStatus={false} title={`规模序列`} />
                 <ScaleTable ref={`scaleTable`} _getUnitList={this._getScaleTableList.bind(this)} />
            </div>

            <div className={`mt_20`}>
                <div className={`${DetailsStyle.split_middle_container}`}>
                    <div className={`container_bg_fff ${DetailsStyle.split_middle_left} mr_5`}>
                        <HeaderTitle iconStatus={true} title={`净值走势`} />
                        <Spin delay={10} spinning={this.state.navLoading} tip={`loading...`}>
                        <CommonCharts idName={`navChart`} ref={`navChart`} styles={{width: '100%', height: '500px'}} />
                        </Spin>
                    </div>
                    <div className={`container_bg_fff ${DetailsStyle.split_middle_right} ml_5`}>
                        <HeaderTitle iconStatus={true}  title={`规模占比走势`} />
                        <Spin delay={10} spinning={this.state.scaleLoading} tip={`loading...`}>
                            <CommonCharts idName={`scaleChart`} ref={`scaleChart`} styles={{width: '100%', height: '500px'}} />
                        </Spin>
                    </div>
                </div>
            </div>

            <div className={`container_bg_fff mt_20 ${DetailsStyle.none_border_container}`}>
                <NoneBorderTitle iconStatus={true } title={`子产品净值模拟`} />
                <SubTable ref={`subTable`} _initData={this._getMockNav.bind(this)} />
            </div>

    </div>)
    }

    // 净值走势图

    async UNSAFE_componentWillMount() {
        await this._getSearchList({
            fund_id: query.id,
            t_date_start: '',
            t_date_end: ''
        })
    }

    async componentDidMount() {
        // 单位净值序列
        this.refs.navTables.initData({fund_id: query.id})
        // 规模序列
        this.refs.scaleTable.initData({fund_id: query.id})
        // 子产品净值模拟
        this.refs.subTable._initData({fund_id: query.id, t_date_end: this.state.endDate, t_date_start: this.state.endDate})
        // 规模占比走势
        await this._getScaleSub({fund_id: query.id, t_date_end: this.state.endDate, t_date_start: this.state.endDate})
        // 净值走势
        await this._getNavChart({fund_id: query.id, t_date_end: this.state.endDate, t_date_start: this.state.endDate})

    }

    // 结束时间选择
    changeEndDate (mo, str) {
        if (str) {
            const startValue = moment(moment(this.state.startDate).format('YYYY-MM-DD')).valueOf()
            const currentValue = moment(moment(str).format('YYYY-MM-DD')).valueOf()
            if (startValue > currentValue) {
                message.destroy()
                message.info('开始时间不能大于结束时间')
                return
            }
            this.setState({endDate: moment(str)}, async () => {
                if (this.state.startDate) {
                    await this._getSearchList({
                        fund_id: query.id,
                        t_date_start: moment(this.state.startDate).format('YYYY-MM-DD'),
                        t_date_end:  moment(this.state.endDate).format('YYYY-MM-DD')
                    })

                    // 单位净值序列
                    await this._initNavTable()
                }
            })
        } else {
            this.setState({endDate: null})
        }
    }
    // 选择开始时间
    changeStartDate (mo, str) {
        if (str) {
            const endValue = moment(moment(this.state.endDate).format('YYYY-MM-DD')).valueOf()
            const currentValue = moment(moment(str).format('YYYY-MM-DD')).valueOf()
            if (currentValue > endValue) {
                message.destroy()
                message.info('开始时间不能大于结束时间')
                return
            }
            this.setState({startDate: moment(str)}, async () => {
                if (this.state.endDate) {
                    await this._getSearchList({
                        fund_id: query.id,
                        t_date_start: moment(this.state.startDate).format('YYYY-MM-DD'),
                        t_date_end:  moment(this.state.endDate).format('YYYY-MM-DD')
                    })
                    // 单位净值序列
                    await this._initNavTable()
                }
            })
        } else {
            this.setState({startDate: null})
        }
    }
    // 集中处理页面请求加载
    async _initNavTable () {
        if (this.state.org_ids.length > 0 && this.state.type_codes.length <= 0) {
            // 净值序列
            this.refs.navTables.initData({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                org_ids: this.state.org_ids,
                type_codes: null
            })
            // 规模序列
            this.refs.scaleTable.initData({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                org_ids: this.state.org_ids,
                type_codes: null
            })
            // 子产品净值模拟
            this.refs.subTable._initData({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                org_ids: this.state.org_ids,
                type_codes: null
            })
            // 规模占比走势
            await this._getScaleSub({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                org_ids: this.state.org_ids,
                type_codes: null
            })
            // 净值走势
            await this._getNavChart({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                org_ids: this.state.org_ids,
                type_codes: null
            })
        }

        if (this.state.type_codes.length > 0 && this.state.org_ids.length <= 0) {
            // 净值序列
            this.refs.navTables.initData({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: this.state.type_codes,
                org_ids: null
            })
            this.refs.scaleTable.initData({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: this.state.type_codes,
                org_ids: null
            })
            this.refs.subTable._initData({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: this.state.type_codes,
                org_ids: null
            })
            // 规模占比走势
            await this._getScaleSub({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: this.state.type_codes,
                org_ids: null
            })
            // 净值走势
            await this._getNavChart({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: this.state.type_codes,
                org_ids: null
            })
        }

        if (this.state.type_codes.length > 0 && this.state.org_ids.length > 0) {
            // 净值序列
            this.refs.navTables.initData({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: this.state.type_codes,
                org_ids: this.state.org_ids
            })
            this.refs.scaleTable.initData({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: this.state.type_codes,
                org_ids: this.state.org_ids
            })
            this.refs.subTable._initData({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: this.state.type_codes,
                org_ids: this.state.org_ids
            })
            // 规模占比走势
            await this._getScaleSub({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: this.state.type_codes,
                org_ids: this.state.org_ids
            })
            // 净值走势
            await this._getNavChart({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: this.state.type_codes,
                org_ids: this.state.org_ids
            })
        }

        if (this.state.type_codes.length <= 0 && this.state.org_ids.length <= 0) {
            // 净值序列
            this.refs.navTables.initData({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: null,
                org_ids: null
            })
            // 规模序列
            this.refs.scaleTable.initData({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: null,
                org_ids: null
            })
            // 子产品模拟净值
            this.refs.subTable._initData({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: null,
                org_ids: null
            })
            // 规模占比走势
            await this._getScaleSub({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: null,
                org_ids: null
            })
            // 净值走势
            await this._getNavChart({
                fund_id: query.id,
                t_date_start: this.state.startDate,
                t_date_end: this.state.endDate,
                type_codes: null,
                org_ids: null
            })
        }
    }

    // 过滤条件点击事件
    async checkSwitch (type, params, e) {
        console.log(type, params)
        e.stopPropagation()
        const currentEle = e.currentTarget, currentClass = e.currentTarget.getAttribute('class')
        if (currentClass) {
            let tempArr = this.state[type]
            tempArr.splice(tempArr.indexOf(params), 1)
            currentEle.setAttribute('class', '')
            await this.setState({[type]: tempArr}, async () => {
                await this._initNavTable()
            })
        } else {
            let tempArr = this.state[type]
            tempArr.push(params)
            currentEle.setAttribute('class', 'customer_select_checked')
            await this.setState({[type]: tempArr}, async () => {
                await this._initNavTable()
            })
        }
    }
    // 重置选择条件
    resetParams (type, e) {
        e.stopPropagation()
        const parent = e.target.parentNode
        this.setState({[type]: []}, async () => {

            const searchEle = parent.querySelectorAll('dd')
            searchEle.forEach(item => {
                item.setAttribute('class', '')
            })
            console.log(this.state[type])
            await this._initNavTable()
        })
    }

    // 获取过滤条件信息
    async _getSearchList (params) {
        await this.setState({switchLoading: true})
        const data = await _getSubSearch(params)
        if (data && data.result && data.status) {
            const orgScreen = data.result.orgScreen, typeScreen = data.result.typeScreen
            await this.setState({
                orgScreen: orgScreen,
                typeScreen: typeScreen,
                switchLoading: false
            })
        }
    }

    // 单位净值序列列表
    async _getUnitTableList (params) {
        const data = await _getUnitList(params)
        message.destroy()
        if (data) {
            console.log(data)
            return data.result
        } else {
            message.info('获取数据失败')
        }
    }

    // 规模序列列表
    async _getScaleTableList (params) {
        const data = await _getScaleList(params)
        if (data) {
            return data.result
        } else {
            message.info('获取数据失败')
        }
    }

    // 资产品信息-净值走势
    async _getNavChart (params) {
        this.setState({navLoading: true}, async () => {
            const data = await _getSubNav(params)
            const lineOptions = JSON.parse(JSON.stringify(linesOptions))
            if (data && data.result && data.status) {
                lineOptions.xAxis[0].data = data.result.x_axis
                // lineOptions.legend.data = data.result.name_list
                lineOptions.yAxis[0].name = '单位净值'

                let tempArr = []
                data.result.y_axis.forEach((item, index) => {
                    tempArr.push({
                        name: item.key,
                        type: 'line',
                        itemStyle: {
                            normal: { color: chartsColors[index % 8] }
                        },
                        data: item.value
                    },)
                })
                lineOptions.series = tempArr
                lineOptions.tooltip.formatter = value => {
                    let itemDesc = `${value[0].name}<br />`
                    value.forEach(item => {
                        if (item.value !== undefined) {
                            itemDesc += `${item.marker}${item.seriesName}: ${isNaN(item.value) ? '--': parseFloat(item.value).toFixed(4)}<br />`
                        }
                    })

                    return itemDesc
                }
            }
            console.log(data, '---净值走势图--')
            this.setState({navLoading: false})
            this.refs.navChart.setOpitions(lineOptions)
        })
    }

    // 子产品信息-规模占比走势
    async _getScaleSub (params) {
        this.setState({scaleLoading: true}, async () => {
            const data = await _getSubScale(params)
            console.log('规模占比走势', data)
            const lineOptions = JSON.parse(JSON.stringify(linesOptions))
            if (data && data.result && data.status) {
                lineOptions.color = chartsColors
                lineOptions.xAxis[0].data = data.result.x_axis
                // lineOptions.legend.data = data.result.name_list
                lineOptions.yAxis[0].name = '规模占比（%）'
                lineOptions.yAxis[0].max = 100

                let tempArr = []
                data.result.y_axis.forEach((item, index) => {
                    tempArr.push({
                        name: item.key,
                        type: 'line',
                        stack: '总量',
                        itemStyle: {
                            normal: { color: chartsColors[index % 8] }
                        },
                        areaStyle: {color: areaColors[index % 8] , normal: {color: areaColors[index % 8]}},
                        data: item.value
                    },)
                })
                lineOptions.series = tempArr
                lineOptions.tooltip.formatter = value => {
                    let itemDesc = `${value[0].name}<br />`
                    value.forEach(item => {
                        if (item.value) {
                            itemDesc += `${item.marker}${item.seriesName}: ${isNaN(item.value) ? '--': parseFloat(item.value).toFixed(2) + '%'}<br />`
                        }
                    })

                    return itemDesc
                }
            }
            this.refs.scaleChart.setOpitions(lineOptions)
            this.setState({scaleLoading: false})
        })

    }

    // 子产品净值模拟
    async _getMockNav (params) {
        const param = { token: '123456', ...params}
        const data = await _getMockNav(param)
        if (data) {
            return data
        } else {
            message.info('获取数据失败')
        }
    }

}
